import { AfterViewInit, Component, ElementRef, OnInit, Output } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, FormArray, NgForm, NgModel, Validators } from '@angular/forms';

import { MatSnackBar } from '@angular/material/snack-bar';

import { takeUntil } from 'rxjs/operators'

import { AuthenticationService } from '../../core/services/authentication.service';
import { CommonService } from '../../core/services/common.service';
import { RegularExpressionConfig } from '../../core/config/regular-expression.config';
import { BaseDirective } from '../../core/models/base-directive.model';
import { ColorConfig } from '../../core/config/color.config';

@Component({
    selector: 'op-login',
    templateUrl: './login.component.html',
    styleUrls: ['../../../assets/styles/hide-element-focus-outline.css']
})
export class LoginComponent extends BaseDirective implements OnInit, AfterViewInit {
    formGroup: FormGroup;
    loginIsSuccessful: boolean = false;
    legitimateAccountOfRegExp = RegularExpressionConfig.legitimateAccount;

    constructor(
        private authenticationService: AuthenticationService,
        private elementRef: ElementRef,
        private formBuilder: FormBuilder,
        public snackBar: MatSnackBar
    ) {
        super();
    }

    ngOnInit(): void {
        super.ngOnInit();

        this.createForm();
        this.loadData();
        this.authenticationService.isAuthenticated$.pipe(takeUntil(this.ngUnsubscribe)).subscribe(data => this.loginIsSuccessful = data);
    }

    ngAfterViewInit(): void {
        this.commonService.appendScriptChildToElement(this.elementRef, ['js/custom-form-float.js']);
    }

    login(event: NgForm): void {
        if (event.valid) {
            this.authenticationService.saveUserInfo(this.formGroup.value);
            setTimeout(() => {
                if (!this.loginIsSuccessful) {
                    let data = { message: '请输入正确的用户名和密码', fontColor: ColorConfig.warning };
                    // this.materialSnackBarService.openSnackBarComponent(data, 2000);
                }
            }, 500);
        } else {
            let data = { message: '请输入用户名、密码', fontColor: ColorConfig.danger };
            // this.materialSnackBarService.openSnackBarComponent(data, 2000);
        }
    }

    private createForm(): void {
        this.formGroup = this.formBuilder.group({
            name: ['', Validators.required],
            password: ['', Validators.required],
            rememberMe: ''
        });
    }

    private loadData(): void {
        this.formGroup.setValue({
            name: null,
            password: null,
            rememberMe: true
        });
    }
}